//
//  PhotosetViewController.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-7-19.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "PhotosetViewController.h"
#import "ViewControllerChooser.h"


@implementation PhotosetViewController

@synthesize photoID;

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.navigationItem.title = (NSLocalizedStringFromTable(@"PHOTOSET",@"main",@""));
	
	[self.navigationItem setRightBarButtonItem:btnAdd];
	
	photosets = [[NSMutableArray alloc] init];
	
	[NSThread detachNewThreadSelector:@selector(loadPhotosets:) toTarget:self withObject:nil];
	
	// 居中设置
	
	CGFloat w = self.view.frame.size.width;
	CGFloat h = self.view.frame.size.height;
	
	CGFloat sw = active.frame.size.width;
	CGFloat sh = active.frame.size.height;
	
	CGFloat sx = (w - sw)/2;
	CGFloat sy = (h - sh)/2 - 50;
	
	[active setFrame:CGRectMake(sx, sy, sw, sh)];
	
	psText = (NSLocalizedStringFromTable(@"PHOTOS",@"main",@""));

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark -
#pragma mark Action

/**
 * 通过按钮进行重新联网
 */
-(IBAction)reloadPhotosets:(id)sender{
	[NSThread detachNewThreadSelector:@selector(loadPhotosets:) toTarget:self withObject:nil];
}

/**
 * 添加新的图片集
 */
-(IBAction)addPhotoSet:(id)sender{
	// TODO 进行图像集创建
	UIViewController *addVC = [[ViewControllerChooser sharedChooser] choose:VCC_ID_PHOTOSET_ADD];
	[self.navigationController pushViewController:addVC animated:YES];
}

//-(void)addPhotoToSet:(id)arg{
//	NSLog(@"Add Photo to Set");
//	loading = YES;
//	PhotosetInfo *psi = (PhotosetInfo *)[photosets objectAtIndex:selectIndex];
//	NSString *psid = psi.setID;
//	DataManager *dm = [DataManager sharedDataManager];
//	BOOL bOK = [dm addPhotoToSet:self.photoID toSet:psid];
//	NSString *aTitle = nil;
//	NSString *aMessage = nil;
//	NSString *aCancel = (NSLocalizedStringFromTable(@"OK",@"main",@""));
//	if(bOK){
//		// TODO 上传成功
//		aTitle = (NSLocalizedStringFromTable(@"OK",@"main",@""));
//		aMessage  = (NSLocalizedStringFromTable(@"PHOTO_TO_SET_SUCCESS",@"main",@""));
//	}else{
//		// TODO 上传失败
//		aTitle = (NSLocalizedStringFromTable(@"ERROR",@"main",@""));
//		aMessage  = (NSLocalizedStringFromTable(@"PHOTO_TO_SET_FAILD",@"main",@""));
//	}
//	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:aTitle message:aMessage delegate:nil cancelButtonTitle:aCancel otherButtonTitles:nil];
//	[alert show];
//	[alert release];
//	loading = NO;
//}

#pragma mark -
#pragma mark Photoset Info loading
-(void)loadPhotosets:(id)arg{
	loading = YES;
	DataManager *dm = [DataManager sharedDataManager];
	if([dm isAuthorized]){
		// TODO 显示进度
		[self performSelectorOnMainThread:@selector(startActive:) withObject:nil waitUntilDone:NO];
		NSArray *ps = [dm getPhotosetsByID:[dm currentUserID]];
		[active stopAnimating];
		[active removeFromSuperview];
		if(ps){
			int con = [ps count];
			if(con > 0){
				[photosets setArray:ps];
				[self performSelectorOnMainThread:@selector(reDisplay:) withObject:nil waitUntilDone:YES];
				PhotosetInfo *pinfo;
				id iobj;
				NSURL *url;
				for (int i = 0; i< con; i++) {
					pinfo = (PhotosetInfo *)[photosets objectAtIndex:i];
					url = [NSURL URLWithString:[pinfo getPhotoURL:PICSIZE_S]];
					iobj = [dm loadPhotoWithURL:url];
					if([iobj isKindOfClass:[UIImage class]]){
						UIImage *img = (UIImage *)iobj;
						pinfo.image = img;
					}else{
						NSLog(@"Load Photoset primary photo error");
					}
				}
				[self performSelectorOnMainThread:@selector(reDisplay:) withObject:nil waitUntilDone:YES];
			}
		}else{
			// TODO 提示出错
			NSString *aTitle = (NSLocalizedStringFromTable(@"ERROR",@"main",@""));
			NSString *aMessage = (NSLocalizedStringFromTable(@"AUTH_ERROR",@"main",@""));
			NSString *aCancel = (NSLocalizedStringFromTable(@"CANCEL",@"main",@""));
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:aTitle message:aMessage delegate:nil cancelButtonTitle:aCancel otherButtonTitles:nil]; 
			[alert show];
			[alert release];
		}		
	}else {		
		NSString *alTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"ERROR",@"main",@""))];
		NSString *alMessage = [NSString stringWithString:(NSLocalizedStringFromTable(@"NEED_AUTH",@"main",@""))];
		NSString *authTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"AUTH",@"main",@""))];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alTitle message:alMessage delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:authTitle,nil];
		[alert show];
		[alert release];
	}

	loading = NO;
}

-(void)startActive:(id)arg{	
	[self.view addSubview:active];
	[active startAnimating];
}


-(void)reDisplay:(id)arg{
	[tableView reloadData];
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return [photosets count];
}

/**
 * 表头标题
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	NSString *ret = nil;
	if(section == 0){
		ret = NSLocalizedStringFromTable(@"YOUR_SETS",@"main",@"");
	}
	return ret;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
		// 针对不同的目标平台进行适配
#ifndef __IPHONE_3_0
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
#else
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
#endif
    }
	
	// cell.selectionStyle = UITableViewCellSelectionStyleNone;
	
	int section = indexPath.section;
	int row = indexPath.row;
	
	if(section == 0){
		// TODO 显示 照片集
		PhotosetInfo *pinfo = (PhotosetInfo *)[photosets objectAtIndex:row];
		
		CGFloat ch = cell.frame.size.height;
		
		// TODO 自定义表格样式
		// 采用一个单元格中包含两小行，一个是标题，一个是，照片数目
		UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(ch+2, 0, 100, 19)];
		lblTitle.text = pinfo.title;
		[cell.contentView addSubview:lblTitle];
		
		UILabel *lblPhotos = [[UILabel alloc] initWithFrame:CGRectMake(ch + 2, lblTitle.frame.size.height + 2, 100, 17)];
		// 组合成图片张数内容
		lblPhotos.text = [NSString stringWithFormat:@"%d %@",pinfo.photos,psText];
		// 设置图片数文字为亮灰色
		lblPhotos.textColor = [UIColor lightGrayColor];
		// 设置为小字体
		lblPhotos.font = [UIFont fontWithName:@"Helvetica" size:13.0];
		[cell.contentView addSubview:lblPhotos];

#ifdef debug
		NSString *primaryPhotoURL = [pinfo getPhotoURL:PICSIZE_S];
		NSLog(primaryPhotoURL);
#endif
		
		if(pinfo.image){
			UIImage *uimage = pinfo.image;
			
#ifndef __IPHONE_3_0
			cell.image = [uimage imageByScalingProportionallyToSize:CGSizeMake(ch,ch)];				
#else
			CGFloat iw = uimage.size.width;
			CGFloat ih = uimage.size.height;
			CGFloat sx = ch / iw;
			CGFloat sy = ch / ih;
			cell.imageView.image = uimage;
			// 使用这种方法可以将图像缩小，但是比例需要检查
			cell.imageView.transform = CGAffineTransformMakeScale(sx, sy);
#endif
		}
		
		[lblPhotos release];
		[lblTitle release];
		
		
//#ifndef __IPHONE_3_0
//		cell.text = pinfo.title;
//#else
//		cell.textLabel.text = pinfo.title;
//#endif
	}
    
    // Set up the cell...
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
    return cell;
}


- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	[table deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark -
#pragma mark UIAlertViewDelegate
/**
 * UIAlertViewDelegate 方法
 */
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	if(buttonIndex == 1){
		UIViewController *authView = [[ViewControllerChooser sharedChooser] choose:VCC_ID_AUTH];
		[self.navigationController pushViewController:authView animated:YES];
	}
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)table canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)table commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)table moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)table canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
	[photosets release];
	[active release];
    [super dealloc];
}


@end

